package com.bestcem.xm.ticket.service.manager.notify;

import com.bestcem.xm.ticket.dao.TicketConfigDao;
import com.bestcem.xm.ticket.dao.dto.TicketInfo;
import com.bestcem.xm.ticket.entity.mongo.Ticket;
import com.bestcem.xm.ticket.entity.mongo.TicketConfig;
import com.bestcem.xm.ticket.entity.mongo.TicketNotifyConfig;
import com.bestcem.xm.ticket.enums.TicketNotifyChannelEnum;
import com.bestcem.xm.ticket.enums.TicketTypeEnum;
import com.bestcem.xm.ticket.grpc.client.TicketBaseUserGrpcService;
import com.bestcem.xm.ticket.grpc.client.dto.user.UserDTO;
import com.bestcem.xm.ticket.service.TicketService;
import com.bestcem.xm.ticket.service.convert.TicketInfoConvert;
import com.bestcem.xm.ticket.task.TicketTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Nonnull;
import javax.annotation.Resource;
import java.util.*;

/**
 * 获取工单通知人地址 工具类
 *
 * @author XiaoYunSong <ys.xiao@idiaoyan.com>
 * @version v1.0
 * @date 2021/11/22 14:44
 */
@Slf4j
@Component
public class AddressManager {

    @Resource
    private TicketTask ticketTask;

    @Resource
    private TicketService ticketService;
    @Resource
    private TicketConfigDao ticketConfigDao;

    @Resource
    private TicketBaseUserGrpcService ticketBaseUserGrpcService;


    /**
     * 获取工单通知接收人地址列表 (消息库版)
     *
     * @param ticket       工单信息
     * @param notifyConfig 通知配置
     * @param channel      通知渠道
     * @return 接收人地址列表
     * @author XiaoYunSong <ys.xiao@idiaoyan.com>
     * @date 2021/11/22 17:03
     */
    @Nonnull
    public Set<String> getReceiverAddress(@Nonnull Ticket ticket, @Nonnull TicketNotifyConfig notifyConfig, TicketNotifyChannelEnum channel) {
        if (Objects.isNull(ticket) || Objects.isNull(notifyConfig)) {
            log.error("[Ticket] getReceiverAddress null error");
            return new HashSet<>();
        }
        if (log.isInfoEnabled()) {
            log.info("[Ticket] getReceiverAddress {}-{}-{}", ticket.getId(), notifyConfig.getId(), channel);
        }

        Set<String> result = new HashSet<>();
        List<UserDTO> users = new ArrayList<>();

        // 预警的处理
        if (TicketTypeEnum.UN_NEED_DEAL.getIndex().equals(ticket.getType())) {
            TicketConfig ticketConfig = ticketConfigDao.findById(ticket.getTicketConfigId());
            // 判断是否通知管理员
            if (Objects.nonNull(ticketConfig) && Boolean.TRUE.equals(ticketConfig.getRemindAdmin())) {
                List<TicketNotifyConfig.ReceiveUser> receiveList = notifyConfig.getReceiverList();
                if (CollectionUtils.isEmpty(receiveList)) {
                    log.error("[Ticket] getReceiverAddress receiveList null {}", receiveList);
                    return new HashSet<>();
                }
                Set<String> receiverIds = new HashSet<>();
                receiveList.forEach(receiveUser -> {
                    if (!ObjectUtils.isEmpty(receiveUser.getId())) {
                        receiverIds.add(receiveUser.getId());
                    }
                });
                // 根据receiverIds 获取用户信息 给receiverUsers赋值
                users = ticketBaseUserGrpcService.listUserByIds(new ArrayList<>(receiverIds));
            }
        }
        // 工单的处理
        if (TicketTypeEnum.NEED_DEAL.getIndex().equals(ticket.getType())) {
            TicketInfo ticketInfo = TicketInfoConvert.entityToInfo(ticket);
            users = ticketService.getCurrentTicketUsers(ticketInfo);
        }

        // 没有收件人就返回
        if (CollectionUtils.isEmpty(users)) {
            log.error("[Ticket] getReceiverAddress 收件人为空 {}", users);
            return new HashSet<>();
        }


        for (UserDTO user : users) {
            // 邮件 | 飞书
            if (TicketNotifyChannelEnum.EMAIL.equals(channel)
                    || TicketNotifyChannelEnum.FEI_SHU.equals(channel)) {
                if (!ObjectUtils.isEmpty(user.getEmail())) {
                    result.add(user.getEmail());
                }
            }
            // 短信
            if (TicketNotifyChannelEnum.SMS.equals(channel)) {
                if (!ObjectUtils.isEmpty(user.getMobile())) {
                    result.add(user.getMobile());
                }
            }
            // 钉钉 | 企业微信
            if (TicketNotifyChannelEnum.DING_TALK.equals(channel) ||
                    TicketNotifyChannelEnum.WECHAT_WORK.equals(channel)) {
                if (!ObjectUtils.isEmpty(user.getId())) {
                    result.add(user.getId());
                }
            }
        }

        return result;
    }


    /**
     * 获取工单通知抄送人地址列表 (消息库版)
     *
     * @param ticket       工单信息
     * @param notifyConfig 通知配置
     * @param channel      通知渠道
     * @return 抄送人地址列表
     * @author XiaoYunSong <ys.xiao@idiaoyan.com>
     * @date 2021/11/22 17:03
     */
    @Nonnull
    public Set<String> getCcAddressNew(@Nonnull Ticket ticket, @Nonnull TicketNotifyConfig notifyConfig, TicketNotifyChannelEnum channel) {
        if (Objects.isNull(ticket) || Objects.isNull(notifyConfig)) {
            log.error("[Ticket] getCcAddressNew null error");
            return new HashSet<>();
        }
        if (log.isInfoEnabled()) {
            log.info("[Ticket] getCcAddressNew {}-{}-{}", ticket.getId(), notifyConfig.getId(), channel);
        }
        if (Objects.isNull(notifyConfig.getHasCcList()) || !notifyConfig.getHasCcList()) {
            if (log.isInfoEnabled()) {
                log.info("[Ticket] getCcAddressNew {} 无抄送人", notifyConfig.getId());
            }
            return new HashSet<>();
        }
        if (CollectionUtils.isEmpty(notifyConfig.getCcList())) {
            if (log.isInfoEnabled()) {
                log.info("[Ticket] getCcAddressNew {} 抄送人列表为空", notifyConfig.getId());
            }
            return new HashSet<>();
        }

        Set<String> result = new HashSet<>();

        // 获取抄送用户
        Set<UserDTO> users = new HashSet<>();
        for (TicketNotifyConfig.RoleRegion roleRegion : notifyConfig.getCcList()) {
            List<UserDTO> userDTOS = ticketTask.getHasPermUserByCc(ticket, roleRegion);
            users.addAll(userDTOS);
        }
        if (log.isInfoEnabled()) {
            log.info("[Ticket] getCcAddressNew 抄送人信息 {}", users);
        }

        if (CollectionUtils.isEmpty(users)) {
            return result;
        }
        for (UserDTO user : users) {
            // 邮件 | 飞书
            if (TicketNotifyChannelEnum.EMAIL.equals(channel)
                    || TicketNotifyChannelEnum.FEI_SHU.equals(channel)) {
                if (!ObjectUtils.isEmpty(user.getEmail())) {
                    result.add(user.getEmail());
                }
            }
            // 短信
            if (TicketNotifyChannelEnum.SMS.equals(channel)) {
                if (!ObjectUtils.isEmpty(user.getMobile())) {
                    result.add(user.getMobile());
                }
            }
            // 钉钉 | 企业微信
            if (TicketNotifyChannelEnum.DING_TALK.equals(channel) ||
                    TicketNotifyChannelEnum.WECHAT_WORK.equals(channel)) {
                if (!ObjectUtils.isEmpty(user.getId())) {
                    result.add(user.getId());
                }
            }
        }

        if (log.isInfoEnabled()) {
            log.info("[Ticket] getCcAddressNew {} 抄送人地址 {}", channel, result);
        }

        return result;
    }

}
